import React, { useEffect, useState } from 'react';
import history from '@/utils/history';

const App = (props) => {
  const [activeRoute, setactiveRoute] = useState(history.location.pathname);

  useEffect(() => {
    // 监听频道发生改变
    const unlisten = history.listen((route) => {
      console.log(activeRoute); //activeRoute 用于别的操作
      setactiveRoute(route.pathname);
    });

    return () => {
      unlisten();
    };
  }, []);

  useEffect(() => {
    setactiveRoute(history.location.pathname);
  }, [history.location.pathname]);

  useEffect(() => {
    if ('scrollRestoration' in window.history) {
      window.history.scrollRestoration = 'manual';
    }
    window.onbeforeunload = function () {
      // 刷新页面滚动条置顶
      window.scrollTo(0, 0);
    };
  }, []);

  history.listen(() => {
    window.scrollTo(0, 0);
  });

  return (
    <div>
      {React.Children.map(props.children, (child) =>
        React.cloneElement(child, { ...props })
      )}
    </div>
  );
};

export default App;
